<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" scroll max-height="600px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="期刊名称" prop="journalName">
        <el-input v-model="formData.journalName" placeholder="请输入期刊名称" clearable maxlength="30" show-word-limit />
      </el-form-item>
      <el-form-item label="期刊编号" prop="journalCode">
        <el-input v-model="formData.journalCode" placeholder="请输入期刊编号" clearable />
      </el-form-item>
      <el-form-item label="ISSN/ISBN" prop="sn">
        <el-input v-model="formData.sn" placeholder="请输入ISSN/ISBN" clearable/>
      </el-form-item>
      <el-form-item label="出版社" prop="journalFrom">
        <el-input v-model="formData.journalFrom" placeholder="请输入出版社" clearable />
      </el-form-item>
      <el-form-item label="语言" prop="language">
        <el-input v-model="formData.language" placeholder="请输入语言" clearable />
      </el-form-item>
      <el-form-item label="出版频率" prop="frequency">
        <el-select
          v-model="formData.frequency"
          placeholder="请选择出版频率"
          clearable
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.JOURNAL_FREQUENCY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主题分类" prop="topicType">
        <el-select
          v-model="formData.topicType"
          placeholder="请选择主题分类"
          clearable
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.JOURNAL_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="期刊封面" prop="mainImage">
        <UploadImg v-model="formData.mainImage" />
      </el-form-item>
      <el-form-item label="期刊文件" prop="file">
        <UploadFile v-model="formData.file" />
      </el-form-item>
      <el-divider content-position="left">版本与卷期</el-divider>
      <el-form-item label="卷号" prop="volumeNumber">
        <el-input v-model="formData.volumeNumber" placeholder="请输入卷号" clearable />
      </el-form-item>
      <el-form-item label="期号" prop="issue">
        <el-input v-model="formData.issue" placeholder="请输入期号" clearable />
      </el-form-item>
      <el-form-item label="期刊发行时间" prop="publishYear">
        <el-date-picker
          v-model="formData.publishYear"
          type="year"
          value-format="YYYY"
          placeholder="请选择期刊发行时间"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="期刊发行地点" prop="position">
        <el-input v-model="formData.position" placeholder="请输入期刊发行地点" clearable />
      </el-form-item>
      <el-form-item label="期刊发行内容" prop="content">
        <el-input v-model="formData.content" type="textarea" placeholder="请输入期刊发行内容" clearable maxlength="200" show-word-limit />
      </el-form-item>
      <el-form-item label="期刊作者" prop="author">
        <el-input v-model="formData.author" placeholder="请输入期刊作者" clearable />
      </el-form-item>
      <el-form-item label="页码范围" prop="pageRange">
        <el-input v-model="formData.pageRange" placeholder="请输入页码范围" clearable />
      </el-form-item>
      <el-divider content-position="left">订购信息</el-divider>
      <el-form-item label="期刊来源" prop="source">
        <el-select
          v-model="formData.source"
          placeholder="请选择期刊来源"
          clearable
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.JOURNAL_SOURCE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="期刊状态" prop="status">
        <el-select
          v-model="formData.status"
          placeholder="请选择期刊状态"
          clearable
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.JOURNAL_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订购来源" prop="orderSource">
        <el-input v-model="formData.orderSource" placeholder="请输入订购来源" clearable />
      </el-form-item>
      <el-form-item label="订购日期" prop="orderTime">
        <el-date-picker
          v-model="formData.orderTime"
          value-format="x"
          type="datetime"
          placeholder="请选择订购日期"
          :default-time="new Date('1 23:59:59')"
          style="width: 100%"
        />
      </el-form-item>
      <el-divider content-position="left">存储信息</el-divider>
      <el-form-item label="访问链接" prop="webUrl">
        <el-input v-model="formData.webUrl" placeholder="请输入访问链接" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { JournalApi, JournalVO } from '@/api/dr/journal'

/** 期刊信息 表单 */
defineOptions({ name: 'JournalForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<JournalVO | any>({
  id: undefined,
  ywid: undefined,
  journalName: undefined,
  journalCode: undefined,
  sn: undefined,
  journalFrom: undefined,
  language: undefined,
  frequency: undefined,
  topicType: undefined,
  mainImage: undefined,
  file: undefined,
  volumeNumber: undefined,
  issue: undefined,
  publishYear: undefined,
  pageRange: undefined,
  source: undefined,
  status: undefined,
  orderSource: undefined,
  orderTime: undefined,
  position: undefined,
  webUrl: undefined,
})
const formRules = reactive({
  journalName: [
    {
      required: true,
      message: '请输入期刊名称',
      trigger: ['blur', 'change'],
    },
  ],
  journalCode: [
    {
      required: true,
      message: '请输入期刊编号',
      trigger: ['blur', 'change'],
    },
  ],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await JournalApi.getJournal(id) || {}
      formData.value.status = formData.value.status + ''
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as JournalVO
    if (formType.value === 'create') {
      await JournalApi.createJournal(data)
      message.success(t('common.createSuccess'))
    } else {
      await JournalApi.updateJournal(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    ywid: undefined,
    journalName: undefined,
    journalCode: undefined,
    sn: undefined,
    journalFrom: undefined,
    language: undefined,
    frequency: undefined,
    topicType: undefined,
    mainImage: undefined,
    file: undefined,
    volumeNumber: undefined,
    issue: undefined,
    publishYear: undefined,
    pageRange: undefined,
    source: undefined,
    status: undefined,
    orderSource: undefined,
    orderTime: undefined,
    position: undefined,
    webUrl: undefined,
  }
  formRef.value?.resetFields()
}
</script>